<?php
/**
 * 
 * @author Elwin
 * 
 * example:
 * $data = new CActiveTreeProvider('Dept', 
 *    array('criteria'=>
 *        array('condition'=>'state=1')
 *    )
 * );
 */
class CActiveTreeProvider extends CActiveDataProvider {
	public $id = '';
	public $parentid = '';
	public $name = '';
	public $sort = '';
	//public $children = '';
	//private $_tree = '';
	
	public function __construct($modelClass, $config = array(), $setting= array()) {
		// 按父节点字段降序显示
		foreach($setting as $key=>$value)
			$this->$key = $value;		
		$config['criteria']->order = $this->parentid. ' ASC';		
		if (!empty($this->sort)) 
			$config['criteria']->order .= ', '.$this->sort.' ASC';
		$config['criteria']->order .= ', '.$this->id.' ASC';		
		// $config['criteria']->limit = 10;
		$config['pagination'] = false;
		parent::__construct ( $modelClass, $config );
		// $data = $this->fetchData();
		// print_r($data);
		// foreach ($data as $model){
			// print_r($model->attributes);
		// }
		
		
	}
	
	public function buildTree($data=array(), $parentid=0){
		if ($parentid > 100) break;
		$branch = array ();
		if (empty($data)){
			$data = $this->fetchData();
			$branch=$data;
		}
		if (!empty($data) && is_array($data)) {
			foreach($data as $key=>$model){
				if ($model->{$this->parentid} == $parentid) {
					self::buildTree($model->attributes, $model->id);
					$data[$key]['children'] = $this->model->findAll(array('condition'=>$this->parentid.'='.$model->id));
					/*if ($children) {
						$data[$key]['children'] = $children;
					}*/
					 $branch [] = $data;
				}
			}
			// break;
		}
		return $branch;
	}
	
	
	public function renderRow(){
		
	}
	
	public function createTree() {
	}
	
	public function getTree(){
		return $this->_tree;
	}
	
	/*public function fetchData(){
		//$data = $this->fetchData();
		//return $data;
	}*/
}
?>